import { FC, useContext, useEffect, useState } from "react";
import styles from "./index.module.less";
import {
  DeviceInfo,
  AlertInfo,
  StatInfo,
  OptimizationSuggestion,
} from "./types";
import {
  AISummary,
  DeviceStatus,
  AlertStatus,
  StatAnalysis,
  OptimizationSuggestions,
} from "./components";
import useWebsocket from "@/hooks/useWebsocket";
import { BigScreenContext } from "@/pages/BigScreen/context/BigScreenContext";

// WebSocket数据接口
interface WebSocketData {
  crackingFurnaceList?: Array<{
    name: string;
    status: number;
    operatingTime: number;
    operatingLoad: number;
  }>;
  abnormalAlarmList?: Array<{
    status: number;
    currentValue: number;
    cumulativeValue: number;
  }>;
  statisticalAnalysisList?: Array<{
    name: string;
    value: string;
    unit: string;
  }>;
  optimizationSuggestionList?: Array<{
    id: string;
    suggestion: string;
    button: string;
  }>;
  summary?: string;
  // 其他可能的字段
}

/**
 * 将裂解炉数据转换为DeviceInfo格式
 * @param crackingFurnaceList 裂解炉数据列表
 * @returns DeviceInfo数组
 */
const convertToDeviceInfos = (
  crackingFurnaceList: WebSocketData["crackingFurnaceList"]
): DeviceInfo[] => {
  if (!crackingFurnaceList || !Array.isArray(crackingFurnaceList)) {
    return [];
  }

  return crackingFurnaceList.map((item: any, index) => {
    // 将数字状态转换为所需的字符串状态
    let statusString:
      | "idle"
      | "running"
      | "warning"
      | "completed"
      | "cleaning"
      | "stop" = "idle";
    if (item.status === 1) {
      statusString = "idle"; // 投炉
    } else if (item.status === 2) {
      statusString = "running"; // 正常运行
      if (item.detailStatus === 50) {
        statusString = "running"; // 正常运行
      } else if (item.detailStatus === 80) {
        statusString = "warning"; // 中度结焦
      } else if (item.detailStatus === 100) {
        statusString = "completed"; // 重度结焦
      }
    } else if (item.status === 3) {
      statusString = "cleaning"; // 清焦
    } else if (item.status === 4) {
      statusString = "stop"; // 停炉
    }

    return {
      id: (index + 1).toString(),
      name: item.name,
      status: statusString,
      runningDays: item.operatingTime, // 运行时间对应为runningDays
      operationRate: item.operatingLoad, // 运行负荷对应为operationRate
    };
  });
};

/**
 * 将异常预警数据转换为AlertInfo格式
 * @param abnormalAlarmList 异常预警数据列表
 * @returns AlertInfo数组
 */
const convertToAlertInfos = (
  abnormalAlarmList: WebSocketData["abnormalAlarmList"]
): AlertInfo[] => {
  if (!abnormalAlarmList || !Array.isArray(abnormalAlarmList)) {
    return [];
  }

  return abnormalAlarmList
    .filter((item) => item.status !== 10)
    .map((item) => {
      // 将数字状态转换为所需的字符串类型
      let typeString: "alarm" | "warning" | "normal" = "normal";
      switch (item.status) {
        case 30:
          typeString = "alarm"; // 报警
          break;
        case 20:
          typeString = "warning"; // 预警
          break;
        case 10:
          typeString = "normal"; // 正常
          break;
      }

      return {
        type: typeString,
        count: item.currentValue, // 当前报警数量
        details: item.cumulativeValue, // 累计发生数量
      };
    });
};

/**
 * 将统计分析数据转换为StatInfo格式
 * @param statisticalAnalysisList 统计分析数据列表
 * @returns StatInfo数组
 */
const convertToStatInfos = (
  statisticalAnalysisList: WebSocketData["statisticalAnalysisList"]
): StatInfo[] => {
  if (!statisticalAnalysisList || !Array.isArray(statisticalAnalysisList)) {
    return [];
  }

  // 定义颜色数组，用于轮流分配不同的颜色
  const colors = ["#4299e1", "#4299e1", "#4cd3c2", "#4cd3c2"];

  return statisticalAnalysisList.map((item, index) => {
    return {
      name: item.name,
      value: item.value,
      unit: item.unit,
      color: colors[index % colors.length], // 循环使用颜色数组
    };
  });
};

/**
 * 根据统计分析数据生成优化建议
 * @param statisticalAnalysisList 统计分析数据列表
 * @returns OptimizationSuggestion数组
 */
const generateOptimizationSuggestions = (
  optimizationSuggestionList: WebSocketData["optimizationSuggestionList"]
): OptimizationSuggestion[] => {
  // 根据统计分析数据生成优化建议
  return (
    optimizationSuggestionList?.map((item, index) => {
      const id = (index + 1).toString();
      return { id, content: item.suggestion, buttonText: item.button };
    }) || []
  );
};

/**
 * 生成默认设备状态数据
 * @returns 默认设备状态数据
 */
const getDefaultDeviceInfos = (): DeviceInfo[] => {
  return [
    {
      id: "1",
      name: "1#裂解炉",
      status: "idle",
      runningDays: 0,
      operationRate: 0,
    },
    {
      id: "2",
      name: "2#裂解炉",
      status: "idle",
      runningDays: 0,
      operationRate: 0,
    },
    {
      id: "3",
      name: "3#裂解炉",
      status: "idle",
      runningDays: 0,
      operationRate: 0,
    },
    {
      id: "4",
      name: "4#裂解炉",
      status: "idle",
      runningDays: 0,
      operationRate: 0,
    },
    {
      id: "5",
      name: "5#裂解炉",
      status: "idle",
      runningDays: 0,
      operationRate: 0,
    },
  ];
};

/**
 * 生成默认预警数据
 * @returns 默认预警数据
 */
const getDefaultAlertInfos = (): AlertInfo[] => {
  return [
    { type: "normal", count: 0, details: 0 },
    { type: "normal", count: 0, details: 0 },
  ];
};

/**
 * 生成默认统计分析数据
 * @returns 默认统计分析数据
 */
const getDefaultStatInfos = (): StatInfo[] => {
  return [
    { name: "装置乙烯收率", value: "--", unit: "%", color: "#4299e1" },
    { name: "乙烯总收率", value: "--", unit: "%", color: "#4299e1" },
    { name: "原料乙烷含量", value: "--", unit: "%", color: "#4cd3c2" },
    { name: "蒸馏进料量", value: "--", unit: "t", color: "#4cd3c2" },
  ];
};

/**
 * 生成默认优化建议数据
 * @returns 默认优化建议数据
 */
const getDefaultOptimizationSuggestions = (): OptimizationSuggestion[] => {
  return [{ id: "1", content: "正在分析并生成优化建议..." }];
};

const QuestionContainer: FC = () => {
  const [data, setData] = useState<WebSocketData | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const { chatRef } = useContext(BigScreenContext);
  // 装置运行数据
  const [deviceInfos, setDeviceInfos] = useState<DeviceInfo[]>(
    getDefaultDeviceInfos()
  );

  // 异常预警数据
  const [alertInfos, setAlertInfos] = useState<AlertInfo[]>(
    getDefaultAlertInfos()
  );

  // 统计分析数据
  const [statInfos, setStatInfos] = useState<StatInfo[]>(getDefaultStatInfos());

  // 优化建议数据
  const [optimizationSuggestions, setOptimizationSuggestions] = useState<
    OptimizationSuggestion[]
  >(getDefaultOptimizationSuggestions());

  // 处理优化建议点击事件
  const handleSuggestionClick = (name: string, itemName: string) => {
    console.log(`点击了: ${itemName}`);
    let match = itemName.match(/(\d+#裂解炉)/); // 匹配 "数字#裂解炉"
    let targetName = match ? match[1] : "";

    if (itemName.includes("路径优化")) {
      // ! 由对话触发切换
      // setCurrentKey("param");
      chatRef?.current?.handleChat(
        `${targetName}投炉升温过程如何优化COT操作路径，在保证安全平稳的前提下更快速的调整到位。`
      );
    } else {
      // ! 由对话触发切换
      // setCurrentKey("path");
      chatRef?.current?.handleChat(
        `针对${targetName}，在当前工况下如何调整操作变量从而提高裂解炉乙烯收率？`
      );
    }
  };
  const { wsData } = useWebsocket({
    socketUrl: `/cnpc-web/customized-service-websocket/indexHome?userId=admin&moduleId=首页展示`,
    isReload: true,
    isLog: true,
    reloadStep: 5,
    isJson: true,
  });

  useEffect(() => {
    if (wsData !== "") {
      console.log("收到WebSocket数据:", wsData);
      setIsLoading(false);

      try {
        // 尝试将字符串解析为JSON对象
        const parsedData: WebSocketData =
          typeof wsData === "string" ? JSON.parse(wsData) : wsData;
        setData(parsedData);

        // 处理裂解炉数据
        const updatedDeviceInfos = convertToDeviceInfos(
          parsedData?.crackingFurnaceList
        );
        if (updatedDeviceInfos.length > 0) {
          setDeviceInfos(updatedDeviceInfos);
        }

        // 处理异常预警数据
        const updatedAlertInfos = convertToAlertInfos(
          parsedData?.abnormalAlarmList
        );
        if (updatedAlertInfos.length > 0) {
          setAlertInfos(updatedAlertInfos);
        }

        // 处理统计分析数据
        const updatedStatInfos = convertToStatInfos(
          parsedData?.statisticalAnalysisList
        );
        if (updatedStatInfos.length > 0) {
          setStatInfos(updatedStatInfos);
        }
        console.log(
          "parsedData?.optimizationSuggestionList",
          parsedData?.optimizationSuggestionList
        );
        // 处理优化建议数据
        const updatedOptimizationSuggestions = generateOptimizationSuggestions(
          parsedData?.optimizationSuggestionList
        );
        if (updatedOptimizationSuggestions.length > 0) {
          setOptimizationSuggestions(updatedOptimizationSuggestions);
        }
      } catch (error) {
        console.error("解析WebSocket数据失败:", error);
      }
    }
  }, [wsData]);

  return (
    <div className={styles["question-container"]}>
      <div className={styles["equipment-status-box"]}>
        <div
          className={`${styles["box-content"]} ${isLoading ? styles["loading"] : ""}`}
        >
          {/* AI总结部分 */}
          <AISummary summary={data?.summary} isLoading={isLoading} />

          {/* 装置运行状态部分 */}
          <DeviceStatus devices={deviceInfos} isLoading={isLoading} />

          {/* 异常预警状态部分 */}
          <AlertStatus alerts={alertInfos} isLoading={isLoading} />

          {/* 统计分析部分 */}
          <StatAnalysis stats={statInfos} isLoading={isLoading} />

          {/* 优化建议部分 */}
          <OptimizationSuggestions
            suggestions={optimizationSuggestions}
            onActionClick={handleSuggestionClick}
            isLoading={isLoading}
          />
        </div>
      </div>
    </div>
  );
};

export default QuestionContainer;
